package com.cty.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @Auther: cty
 * @Date: 2020/3/12 17:14
 * @Description:  控制器  下载
 * @version: 1.0
 */
@Controller
public class DemoController {
    @RequestMapping("download")
    public void download(String fileName, HttpServletResponse resp, HttpServletRequest req) throws IOException {
        // 1 设置响应头，设置为下载模式
        // attachment表示以附件形式下载；链接的响应头默认为inline，能显示就显示，不能显示就下载
        resp.setHeader("Content-Disposition", "attachment;fileName="+fileName);
        // 2 获取目标文件并转化为二进制流
        String path = req.getServletContext().getRealPath("files");
        File file = new File(path, fileName);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        // 3 把二进制流放到响应体中
        ServletOutputStream os = resp.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();
    }
}
